import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';

interface FileItem {
    name: string;
    type: 'file' | 'directory';
    size?: number;
    modifiedTime: Date;
    path: string;
}

export async function GET(request: NextRequest) {
    try {
        const { searchParams } = new URL(request.url);
        const currentPath = searchParams.get('path') || '';
        const sortBy = searchParams.get('sortBy') || 'name';
        const sortOrder = searchParams.get('sortOrder') || 'asc';
        const search = searchParams.get('search') || '';

        const baseDir = path.join(process.cwd(), 'storage');
        const targetPath = path.join(baseDir, currentPath);

        // 确保目录存在
        try {
            await fs.access(targetPath);
        } catch {
            await fs.mkdir(targetPath, { recursive: true });
        }

        const items = await fs.readdir(targetPath, { withFileTypes: true });

        const fileList: FileItem[] = [];

        for (const item of items) {
            const itemPath = path.join(targetPath, item.name);
            const relativePath = path.join(currentPath, item.name).replace(/\\/g, '/');

            // 过滤搜索
            if (search && !item.name.toLowerCase().includes(search.toLowerCase())) {
                continue;
            }

            if (item.isDirectory()) {
                fileList.push({
                    name: item.name,
                    type: 'directory',
                    modifiedTime: new Date(),
                    path: relativePath
                });
            } else if (item.isFile()) {
                const stats = await fs.stat(itemPath);
                const ext = path.extname(item.name).toLowerCase();

                // 只显示模型文件
                if (ext === '.glb' || ext === '.gltf') {
                    fileList.push({
                        name: item.name,
                        type: 'file',
                        size: stats.size,
                        modifiedTime: stats.mtime,
                        path: relativePath
                    });
                }
            }
        }

        // 排序
        fileList.sort((a, b) => {
            let comparison = 0;

            if (sortBy === 'name') {
                comparison = a.name.localeCompare(b.name);
            } else if (sortBy === 'type') {
                comparison = a.type.localeCompare(b.type);
            } else if (sortBy === 'size') {
                comparison = (a.size || 0) - (b.size || 0);
            } else if (sortBy === 'modifiedTime') {
                comparison = a.modifiedTime.getTime() - b.modifiedTime.getTime();
            }

            return sortOrder === 'asc' ? comparison : -comparison;
        });

        return NextResponse.json({
            success: true,
            data: fileList,
            currentPath
        });
    } catch (error) {
        console.error('Error listing files:', error);
        return NextResponse.json(
            { success: false, error: '获取文件列表失败' },
            { status: 500 }
        );
    }
} 